//
//  ZCLoginViewController.m
//  Unicom
//
//  Created by increase on 16/1/12.
//  Copyright © 2016年 increase. All rights reserved.
//

#import "ZCLoginViewController.h"
#import "ZCMainViewController.h"
#import "MyMD5.h"
@interface ZCLoginViewController ()<NSURLConnectionDelegate, NSURLConnectionDataDelegate>

{
    NSMutableData   *_serverData;
}
@property (nonatomic, assign) BOOL select;
@property (nonatomic, strong) UITextField *userText;
@property (nonatomic, strong) UITextField *passwordText;

@end

@implementation ZCLoginViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (!([[[NSUserDefaults standardUserDefaults] objectForKey:@"url"] isEqualToString:@""] || [[NSUserDefaults standardUserDefaults] objectForKey:@"url"] == NULL)) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    }
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"中国联通资源管理";
    [self initViews];
//    self.select = NO;
    //判断是否记住密码
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"choose"] == 1) {
        UIImageView *imgView = (UIImageView *)[self.view viewWithTag:1001];
        [imgView setImage:[UIImage imageNamed:@"iconfont-duihao"]];
        self.userText.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
        self.passwordText.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwd"];
        NSLog(@"记住密码");
    } else {
        NSLog(@"忘记密码");
    }
    
}

- (void)initViews
{
    UIImageView *logoImg = [[UIImageView alloc] initWithFrame:CGRectMake(320, 30, 40, 40)];
    [self.view addSubview:logoImg];
    logoImg.layer.cornerRadius = 10;
    logoImg.layer.masksToBounds = YES;
    [logoImg setImage:[UIImage imageNamed:@"logo"]];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 90, 300, 30)];
    titleLabel.text = @"中国联通网络资源管理";
    titleLabel.textColor = [UIColor redColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [self.view addSubview:titleLabel];
    
    
    self.userText = [[UITextField alloc] initWithFrame:CGRectMake(10, 150, 375 - 20, 50)];
    self.userText.borderStyle = UITextBorderStyleRoundedRect;
    self.userText.placeholder = @"用户名";
    [self.view addSubview:self.userText];
    
    self.passwordText = [[UITextField alloc] initWithFrame:CGRectMake(10, 205, 375 - 20, 50)];
    self.passwordText.borderStyle = UITextBorderStyleRoundedRect;
    self.passwordText.placeholder = @"密码";
    self.passwordText.secureTextEntry = YES;
    [self.view addSubview:self.passwordText];
    
    //记住密码
    UIView *sureView = [[UIView alloc] initWithFrame:CGRectMake(20, 290, 30, 30)];
    sureView.layer.cornerRadius = 5;
    sureView.backgroundColor = [UIColor lightGrayColor];
    sureView.layer.masksToBounds = YES;
    sureView.layer.borderColor = [UIColor grayColor].CGColor;
    [self.view addSubview:sureView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [sureView addGestureRecognizer:tap];
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    imgView.tag = 1001;
    [sureView addSubview:imgView];
    
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 290, 200, 30)];
    textLabel.text = @"记住用户名和密码";
    textLabel.textColor = [UIColor redColor];
    [self.view addSubview:textLabel];
    
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(10, 400, 355, 50);
    [self.view addSubview:loginBtn];
    [loginBtn setTitle:@"登陆" forState:0];
    loginBtn.titleLabel.textColor = [UIColor whiteColor];
    loginBtn.showsTouchWhenHighlighted = YES;
    loginBtn.backgroundColor = [UIColor redColor];
    [loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    
}


//loginAction
- (void)loginAction
{
    NSLog(@"登陆");
   

    //拼接网址
    
    
    
    NSString *urlString = [NSString stringWithFormat:@"http://%@pdaLogin!login.interface",[[NSUserDefaults standardUserDefaults] objectForKey:@"url"]];

    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setTimeoutInterval:5.0];
    
    [request setHTTPMethod:@"post"];
    
    NSString *pwdStr = [MyMD5 md5:self.passwordText.text];
    NSString *md5 = [pwdStr substringToIndex:24];
    md5 = [md5 substringFromIndex:8];
    md5 = [md5 uppercaseString];
    
    
    
    NSString *bodyStr = [NSString stringWithFormat:@"jsonRequest={username:\"%@\",password:\"%@\",phoneNumber:\"18940033425\"}", self.userText.text, md5];
    NSData *body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@", bodyStr);
    
    [request setHTTPBody:body];
    
    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    [conn start];
//
}

//tapAction
- (void)tapAction
{
    
    UIImageView *imgView = (UIImageView *)[self.view viewWithTag:1001];
    self.select = !self.select;
    
    [[NSUserDefaults standardUserDefaults] setBool:self.select forKey:@"choose"];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"choose"] == 1) {
        NSLog(@"%d", self.select);
        [imgView setImage:[UIImage imageNamed:@"iconfont-duihao"]];
        //记录账号 密码
//        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//        [user setObject:self.userText.text forKey:@"user"];
//        
//        NSString *pwdStr = self.passwordText.text;
//        NSUserDefaults *pwd = [NSUserDefaults standardUserDefaults];
//        [pwd setObject:pwdStr forKey:@"pwd"];
        
        
    } else if (self.select == 0){
        NSLog(@"%d", self.select);
        [imgView setImage:[UIImage imageNamed:@""]];
    }

    
}



//键盘回收
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark - 连接代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"开始接受服务器的返回请求%@", response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    _serverData = [NSMutableData data];
    [_serverData appendData:data];
    
    NSLog(@"中间接收的数据：%@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *string = [[NSString alloc]initWithData:_serverData encoding:NSUTF8StringEncoding];
    NSLog(@"connectionDidFinishLoading解码后的字符串是：%@", string);
    
   
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:_serverData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@", jsonObject);
    NSUserDefaults *uid = [NSUserDefaults standardUserDefaults];
    [uid setObject:jsonObject[@"info"] forKey:@"uid"];
    
    if ([[uid objectForKey:@"uid"] isEqualToString:@"用户名或密码错误。"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"用户名或密码错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    } else {
         NSLog(@"%@登录成功" ,[uid objectForKey:@"uid"]);
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:self.userText.text forKey:@"user"];
        
        NSString *pwdStr = self.passwordText.text;
        NSUserDefaults *pwd = [NSUserDefaults standardUserDefaults];
        [pwd setObject:pwdStr forKey:@"pwd"];

        ZCMainViewController *mainVC = [[ZCMainViewController alloc] init];
        [self.navigationController pushViewController:mainVC animated:YES];
    }
    
   
    
}

// 网络请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"失败 %@", error.localizedDescription);
    
    _serverData = nil;
}

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    NSLog(@"2222222：");
    NSLog(@"发送数据 %ld %ld %ld", (long)bytesWritten, (long)totalBytesWritten, (long)totalBytesExpectedToWrite);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
